package com.gem.taskplan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.DialogTool;
import com.gem.taskplan.service.JsonPackage;
import com.gem.taskplan.service.ReceiveMessageService;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;
import com.gem.taskplan.util.Tools;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class WorkTableActivity extends Activity {
	private String urlQueryTeam = "/SetServlet";		//查询团队路径
	private static String url = "/ProjectServlet";		//查询项目路径
	private EditText projectName = null;				//项目名称
	private ImageView addWorkImage ;   					//添加工作按钮
	private static ImageView userImage;     			//用户头像，点击可以修改个人资料
	private TextView timeText = null;  					//截止时间
	private RelativeLayout time = null;     					//设置时间
	private ImageView  addTeamImgaeDownPop = null;  	//选择团队时，方向箭头图片
	private RelativeLayout teamRelativeLayout = null;	//点击后弹出框
	private View popView = null;						//用来获取popupwindow所在的布局文件（XML）
	private PopupWindow popupWindow  = null;			//弹出窗
	private ListView teamListView ;        				//popupwindow弹出窗中显示的listview
	private View addworkDialog = null;   				//addworkDialog的布局文件
	private TextView teamText = null;					//保存添加的团队
	private View footer = null;							//添加团队弹出框的listview footer
	private RelativeLayout addTeamRL = null;			//添加团队点击控件
	private View view = null;
	private View view1 = null;
	private static List<Map<String, String>> list = new ArrayList<Map<String,String>>();
	private ListView dataListView = null;
	private static SimpleAdapter adapter = null;
	private SharedPreferences sharedPreferences;       //得到保存的信息
	private static String curUserName = null;                 //当前登陆名
	private SwipeRefreshLayout refreshWorkTable = null;//下拉刷新
	private LayoutInflater inflater;
	private Button sureAddWork;							//添加项目对话框的确定按钮
	private Button cancelAddWork;						//添加项目对话框的取消按钮
	private static FinalBitmap fb = null;				//加载用户头像
	private long mExitTime;
	private static Context context ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_work_table);
		
		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);
		
		
		/************获得访问服务器的地址***************/
		url = "/ProjectServlet";
		url = PropertiesUtil.getServerURL(this)+url;
		urlQueryTeam = PropertiesUtil.getServerURL(this)+urlQueryTeam;
		System.out.println("工作台访问服务器地址：--------------"+url);
		context = WorkTableActivity.this;
		//获取登陆名
		sharedPreferences = WorkTableActivity.this.getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE);
		curUserName = sharedPreferences.getString("lastUser", "");
		addWorkImage = (ImageView) findViewById(R.id.addWork);
		userImage = (ImageView) findViewById(R.id.userImage);
		dataListView = (ListView) findViewById(R.id.workList);
		//找到下拉刷新的id
		refreshWorkTable = (SwipeRefreshLayout) findViewById(R.id.refreshWorkTable);
		refreshWorkTable.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_green_light,
				android.R.color.holo_blue_bright, android.R.color.holo_orange_light);//添加刷新颜色变化
		inflater = getLayoutInflater();
		//添加项目
		addWorkImage.setOnClickListener(new ImageViewClickListener());
		//个人设置
		userImage.setOnClickListener(new UserimageClickListener());
		
		
		initList();//初始化list集合
		
		
		adapter = new SimpleAdapter(this, list, R.layout.work_list_main,
				new String[]{"name","out_Time","creator","team"}, new int[]{R.id.workName_tv,R.id.outOfTime_tv,R.id.creator,R.id.relativeTeam});
		dataListView.setAdapter(adapter);
		/**************dataListView点击事件****************/
		dataListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(WorkTableActivity.this,TaskActivity.class);
				TextView projectName = (TextView) arg1.findViewById(R.id.workName_tv);
				intent.putExtra("projectName", projectName.getText().toString());
				intent.putExtra("teamName", list.get(arg2).get("team"));
				startActivity(intent);
			}
		});
		/**************dataListView长按事件****************/
		dataListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View itemView,
					int pos, long arg3) {

				View longClick = inflater.inflate(R.layout.edit_config, null);
				final TextView oldprojectName = (TextView) itemView.findViewById(R.id.workName_tv);
				final String oldProjectName = oldprojectName.getText().toString();//保存当前项目名
				final TextView oldoutOfTime = (TextView) itemView.findViewById(R.id.outOfTime_tv);
				final TextView relativeTeam = (TextView) itemView.findViewById(R.id.relativeTeam);

				final int position = pos;
				final Dialog dialog1 = new AlertDialog.Builder(WorkTableActivity.this).setView(longClick).create();
				dialog1.show();
				dialog1.getWindow().setLayout(250, 300);

				TextView delete = (TextView) longClick.findViewById(R.id.deleteCheckBox);
				TextView edit = (TextView) longClick.findViewById(R.id.editCheckBox);
				/*********编辑项目**********/
				edit.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {

						//判断该用户是否是项目创建者
						Map<String , String> map = new HashMap<String, String>();
						map.put("oldProjectName", oldProjectName);
						map.put("curUser", curUserName);
						map.put("action", "checkedCreator");
						/***********判断是否连接网络**********************/
						if(!CheckedNetWork.checkedConnection(WorkTableActivity.this)){
							return;
						}
						String result = null;
						try {
							result = HttpUtil.postRequest(url, map);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(result.equals("yes")){//登陆用户是该任务的创建者
							view = inflater.inflate(R.layout.addwork_dialog, null);
							
//							view = inflater.inflate(R.layout.addwork_dialog, null);
							sureAddWork = (Button) view.findViewById(R.id.sureAddWork);
							cancelAddWork = (Button) view.findViewById(R.id.cancelAddWork);
							
							teamText = (TextView) view.findViewById(R.id.teamText);
							addTeamImgaeDownPop = (ImageView) view.findViewById(R.id.addTeamImgaeDownPop);
							teamRelativeLayout = (RelativeLayout) view.findViewById(R.id.teamRelativeLayout);
							teamRelativeLayout.setOnClickListener(new chooseTeamSetOnClickListener());
							final EditText projectName = (EditText) view.findViewById(R.id.projectName_et);
							final TextView outOfTime = (TextView) view.findViewById(R.id.outOfTime_et);
							final EditText projectContent = (EditText) view.findViewById(R.id.objectContent_et);
							final TextView teamText = (TextView) view.findViewById(R.id.teamText);
							System.out.println(projectName+"*********"+outOfTime+"**********"+projectContent);  

							//显示改变前的值
							projectName.setText(oldProjectName);
							outOfTime.setText(oldoutOfTime.getText().toString());
							teamText.setText(relativeTeam.getText().toString());
							//Map< String , String> map = new HashMap<String, String>();
							map.clear();
							map.put("action", "getProject_note");  
							map.put("project_name", projectName.getText().toString());
							String objectContent_et = httpSend(map);//获取之前条目的备注
							projectContent.setText(objectContent_et);
							//--------------------------------------------------------------
							time = (RelativeLayout) view.findViewById(R.id.time);
							//掉用Dialogtool类得到时间选择器
							DialogTool dialogTool = new DialogTool(WorkTableActivity.this);
							dialogTool.getTimeDialog(outOfTime,time);

							final AlertDialog dialog = new AlertDialog.Builder(WorkTableActivity.this).setTitle("修改项目").setView(view).create();
							dialog.show();
									sureAddWork.setOnClickListener(new View.OnClickListener() {
										
										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub

											String[] markarray = new String[]{"项目名称","截止时间","项目内容",
													"创建时间","创建者","关联团队"};//map中key值数组
											final String projectName_et = projectName.getText().toString();
											final String outOfTime_et = outOfTime.getText().toString();
											final String projectContent_et = projectContent.getText().toString();
											final String outOfTimesString = Tools.getSystemTime();
											final String team = teamText.getText().toString();

											String[] array = new String[]{projectName_et,outOfTime_et,projectContent_et,outOfTimesString,curUserName,team};
											//调用Json封装函数，把数据封装成Json字符串
											String projectJsonString = JsonPackage.getProjectJson(array,markarray);
											//请求服务器

											Map<String , String> map = new HashMap<String, String>();
											map.put("projectJsonString", projectJsonString);
											map.put("oldProjectName", oldProjectName);
											map.put("action", "updata");
											/***********判断是否连接网络**********************/
											if(!CheckedNetWork.checkedConnection(WorkTableActivity.this)){
												return;
											}
											String result = null;
											try {
												result = HttpUtil.postRequest(url, map);
												System.out.println("-----------------"+result);
											} catch (Exception e) {
												e.printStackTrace();
											}
											if (result.equals("yes")) {
												Toast.makeText(WorkTableActivity.this, "修改项目成功！", Toast.LENGTH_SHORT).show();
												Map<String, String> map1 = new HashMap<String, String>();

												map1.put("name", projectName_et);
												map1.put("out_Time", outOfTime_et);
												map1.put("creator", curUserName);
												map1.put("team", team);
												list.set(position, map1);
												//通知刷新
												adapter.notifyDataSetChanged();
											}else {
												Toast.makeText(WorkTableActivity.this, "修改项目失败！", Toast.LENGTH_SHORT).show();
											}
											dialog1.cancel();
											dialog.cancel();
										}
									});
									cancelAddWork.setOnClickListener(new View.OnClickListener() {
										
										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											dialog.cancel();
										}
									});
									/*.setPositiveButton("确定", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											String[] markarray = new String[]{"项目名称","截止时间","项目内容",
													"创建时间","创建者","关联团队"};//map中key值数组
											final String projectName_et = projectName.getText().toString();
											final String outOfTime_et = outOfTime.getText().toString();
											final String projectContent_et = projectContent.getText().toString();
											final String outOfTimesString = Tools.getSystemTime();
											final String team = teamText.getText().toString();

											String[] array = new String[]{projectName_et,outOfTime_et,projectContent_et,outOfTimesString,curUserName,team};
											//调用Json封装函数，把数据封装成Json字符串
											String projectJsonString = JsonPackage.getProjectJson(array,markarray);
											//请求服务器

											Map<String , String> map = new HashMap<String, String>();
											map.put("projectJsonString", projectJsonString);
											map.put("oldProjectName", oldProjectName);
											map.put("action", "updata");
											*//***********判断是否连接网络**********************//*
											if(!CheckedNetWork.checkedConnection(WorkTableActivity.this)){
												return;
											}
											String result = null;
											try {
												result = HttpUtil.postRequest(url, map);
												System.out.println("-----------------"+result);
											} catch (Exception e) {
												e.printStackTrace();
											}
											if (result.equals("yes")) {
												Toast.makeText(WorkTableActivity.this, "修改项目成功！", Toast.LENGTH_SHORT).show();
												Map<String, String> map1 = new HashMap<String, String>();

												map1.put("name", projectName_et);
												map1.put("out_Time", outOfTime_et);
												map1.put("creator", curUserName);
												map1.put("team", team);
												list.set(position, map1);
												//通知刷新
												adapter.notifyDataSetChanged();
											}else {
												Toast.makeText(WorkTableActivity.this, "修改项目失败！", Toast.LENGTH_SHORT).show();
											}
											dialog1.cancel();
										}
									}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											dialog.cancel();
										}
									}).create();
							dialog.show();*/
						}else {
							dialog1.cancel();
							Toast.makeText(WorkTableActivity.this, "您不是项目的创建者，不能修改此项目！", Toast.LENGTH_SHORT).show();
							return;//登陆用户不是该项目的创建者
						}
					}
				});
				delete.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Map<String , String> map = new HashMap<String, String>();
						map.put("oldProjectName", oldProjectName);
						map.put("curUser", curUserName);
						map.put("action", "checkedCreator");
						
						/***********判断是否连接网络**********************/
						if(!CheckedNetWork.checkedConnection(WorkTableActivity.this)){
							return;
						}
						
						String result = null;
						try {
							result = HttpUtil.postRequest(url, map);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(result.equals("yes")){//登陆用用户是该任务的创建者

						//map = new HashMap<String, String>();
							map.clear();
						map.put("oldProjectName", oldProjectName);
						map.put("action", "delete");
						result = null;
						try {
							result = HttpUtil.postRequest(url, map);
							System.out.println("-----------------"+result);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if (result.equals("yes")) {
							Toast.makeText(WorkTableActivity.this, "删除项目成功！", Toast.LENGTH_SHORT).show();
							//移除项目
							list.remove(position);
							//通知刷新
							adapter.notifyDataSetChanged();
						}else {
							Toast.makeText(WorkTableActivity.this, "删除项目失败！", Toast.LENGTH_SHORT).show();
						}
						dialog1.cancel();
						}else {
							dialog1.cancel();
							Toast.makeText(WorkTableActivity.this, "您不是项目的创建者，不能修改此项目！", Toast.LENGTH_SHORT).show();
							return;//登陆用户不是该项目的创建者
						}
					}
				});
				return false;
			}
		});
		/*************dataListView下拉刷新************/
		refreshWorkTable.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				refreshWorkTable.setRefreshing(false);
				list.clear();
				initList();
			}
		});
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if(requestCode==2&&data!=null){
			String teamName = data.getStringExtra("TeamName");
			if (teamName==null) {
				return;
			}else {
				teamText.setText(teamName);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	/*************发送请求************/
	public String httpSend(Map<String, String> map){
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/*************个人设置按钮点击事件************/
	private class UserimageClickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(WorkTableActivity.this,UserActivity.class);
			intent.putExtra("userName", "userName");
			startActivity(intent);
		}
	}
	/*************添加项目按钮点击事件************/
	private class ImageViewClickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			LayoutInflater inflater = LayoutInflater.from(WorkTableActivity.this);
			
			view1 = inflater.inflate(R.layout.addwork_config, null);
			view = inflater.inflate(R.layout.addwork_dialog, null);
			
			sureAddWork = (Button) view.findViewById(R.id.sureAddWork);
			cancelAddWork = (Button) view.findViewById(R.id.cancelAddWork);
			LinearLayout addWorkHead = (LinearLayout) view1.findViewById(R.id.addWorkHead);
			
			ListView listView = (ListView) view.findViewById(R.id.addWorkListView);
			
			listView.addHeaderView(addWorkHead);
			ArrayAdapter arrayAdapter = new ArrayAdapter(WorkTableActivity.this,android.R.layout.simple_list_item_checked);
			listView.setAdapter(arrayAdapter);
			teamText = (TextView) view.findViewById(R.id.teamText);
			projectName = (EditText) view.findViewById(R.id.projectName_et);
			addTeamImgaeDownPop = (ImageView) view.findViewById(R.id.addTeamImgaeDownPop);
			//创建DialogTool工具类的的对象
			DialogTool dialogTool = new DialogTool(WorkTableActivity.this);
			//调用DialogTool类得到创建项目的弹出窗口
			/***********************添加项目dialog************************************/
			final Dialog addWorkDialog = new Dialog(WorkTableActivity.this);
			addWorkDialog.setTitle("添加项目");
			addWorkDialog.setContentView(view);
			WindowManager manager = getWindowManager();
			Tools.dialogHightWidth(addWorkDialog, manager);
			/*final AlertDialog addWorkDialog = new AlertDialog.Builder(WorkTableActivity.this)
			.setTitle("添加项目").setView(view).create();
			addWorkDialog.show();
			addWorkDialog.getWindow().setLayout(480, 680);*/
			
			teamRelativeLayout = (RelativeLayout) view.findViewById(R.id.teamRelativeLayout);
			//添加团队点击事件
			teamRelativeLayout.setOnClickListener(new chooseTeamSetOnClickListener());
			time = (RelativeLayout) view.findViewById(R.id.time);
			timeText = (TextView) view.findViewById(R.id.outOfTime_et);
			//掉用Dialogtool类得到时间选择器
			dialogTool.getTimeDialog(timeText,time);
			cancelAddWork.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					addWorkDialog.cancel();
				}
			});
			sureAddWork.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					String[] markarray = new String[]{"项目名称","截止时间","项目内容",
							"创建时间","创建者","关联团队"};//map中key值数组
					projectName = (EditText) view.findViewById(R.id.projectName_et);//项目名称
					timeText = (TextView) view.findViewById(R.id.outOfTime_et);//截止时间
					EditText projectContent = (EditText) view.findViewById(R.id.objectContent_et);//项目内容
					TextView teamText = (TextView) view.findViewById(R.id.teamText);

					final String projectName_et = projectName.getText().toString();
					final String outOfTime_et = timeText.getText().toString();
					final String projectContent_et = projectContent.getText().toString();
					final String teamString = teamText.getText().toString();
					final String outOfTimesString = timeText.getText().toString();

					System.out.println("workTableActivity界面截止时间：--"+outOfTimesString);
					if (projectName_et.length()==0) {
						Toast.makeText(WorkTableActivity.this, "您创建的项目或者关联团队是空的！", Toast.LENGTH_LONG).show();
						return;
					}else if (teamString.length()==0){
						Toast.makeText(WorkTableActivity.this, "您创建的项目关联团队是空的！", Toast.LENGTH_LONG).show();
						return;
					}else if(outOfTimesString.length()==0) {
						Toast.makeText(WorkTableActivity.this, "您创建的项目的截止时间是空的！", Toast.LENGTH_LONG).show();
						return;
					}
					String[] array = new String[]{projectName_et,outOfTime_et,projectContent_et,outOfTimesString,curUserName,teamString};
					//调用Json封装函数，把数据封装成Json字符串
					String projectJsonString = JsonPackage.getProjectJson(array,markarray);
					System.out.println("_________________"+projectJsonString);
					//请求服务器
					Map<String , String> map = new HashMap<String, String>();
					map.put("projectJsonString", projectJsonString);
					map.put("action", "add");
					String result = null;
					/***********判断是否连接网络**********************/
					if(!CheckedNetWork.checkedConnection(WorkTableActivity.this)){
						return;
					}
					
					try {
						result = HttpUtil.postRequest(url, map);
						System.out.println("+++++++++++++++++"+result);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (result.equals("yes")) {
						Toast.makeText(WorkTableActivity.this, "添加项目成功！", Toast.LENGTH_SHORT).show();
						Map<String, String> map1 = new HashMap<String, String>();
						map1.put("name", projectName_et);
						map1.put("out_Time", outOfTime_et);
						map1.put("creator", curUserName);
						map1.put("team", teamString);
						list.add(0, map1);
						//数据刷新
						adapter.notifyDataSetChanged();
					}else {
						Toast.makeText(WorkTableActivity.this, "添加项目失败！", Toast.LENGTH_SHORT).show();
					}
					AlertDialog alertDialog = new AlertDialog.Builder(WorkTableActivity.this)
					.setTitle("您想创建任务吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							addWorkDialog.cancel();
							Intent intent = new Intent(WorkTableActivity.this,TaskActivity.class);
							intent.putExtra("projectName", projectName_et);
							startActivity(intent);
						}
					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							addWorkDialog.cancel();
						}
					}).create();
					
					alertDialog.show();
				}
			});
		}
	}
	/*************选择团队************/
	private class chooseTeamSetOnClickListener implements OnClickListener{
		
		@Override
		public void onClick(View v) {
			/***********判断是否连接网络**********************/
			if(!CheckedNetWork.checkedConnection(WorkTableActivity.this)){
				return;
			}
			LayoutInflater inflater = LayoutInflater.from(WorkTableActivity.this);
			List<Map<String, String>> list1 = new ArrayList<Map<String,String>>();
			Map<String, String> map = new HashMap<String, String>();
			map.put("curName", curUserName);
			map.put("action", "queryTeam");
			String result = null;
			try {
				result = HttpUtil.postRequest(urlQueryTeam, map);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				System.out.println("*******所有团队******"+result);
				JSONObject jsonObject = new JSONObject(result);
				JSONArray jsonArray1 = jsonObject.getJSONArray("teamListJson");
				list1.clear();
				for(int i = 0;i<jsonArray1.length();i++){
					JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
					JSONArray jsonArray2 = jsonObject1.getJSONArray("teamListJson"+i);
					String team_name = jsonArray2.getJSONObject(0) .getString("team_name");
//					String team_admin = jsonArray2.getJSONObject(1) .getString("team_admin");
//					String admin_src = jsonArray2.getJSONObject(2) .getString("admin_src");
					Map<String, String> map2 = new HashMap<String, String>();
					map2.put("team", team_name);
//					map2.put("teamLeaderName",team_admin);
//					map2.put("url", admin_src);
					list1.add(map2);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			//刷新数据
			SimpleAdapter simpleAdapter = new SimpleAdapter(WorkTableActivity.this, list1, R.layout.team_popupwindow_choose, new String[]{"team"}, new int[]{R.id.chooseTeam});
			//关联团队的弹出框布局文件
			popView = inflater.inflate(R.layout.addteam_popup, null);
			teamListView = (ListView) popView.findViewById(R.id.teamListView);
			popupWindow = new PopupWindow(popView, 200, 200,true);
			addTeamImgaeDownPop.setImageResource(R.drawable.listinfo_pupwindow);
			int xoff = popupWindow.getWidth() / 2 - teamRelativeLayout.getWidth() / 2;  
			// 将pixels转为dip  
			popupWindow.setFocusable(true);
			popupWindow.setOutsideTouchable(true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.showAsDropDown(teamRelativeLayout, -xoff, 0);
			//弹出框中listview的footer布局文件
			footer = inflater.inflate(R.layout.addteam_popupwindow_footer, null);
			addTeamRL = (RelativeLayout) footer.findViewById(R.id.addTeamImage);
			teamListView.addFooterView(footer);
			teamListView.setAdapter(simpleAdapter);
			System.out.println("==========================");
			addTeamRL.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(WorkTableActivity.this,AddTeamActivity.class);
					//					intent.putExtra("projectName", projectName.getText().toString());
					//					System.out.println("////////////////////////////"+projectName.getText().toString());
					popupWindow.dismiss();
					startActivityForResult(intent, 2);
				}
			});
			teamListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View view,
						int position, long arg3) {
					System.out.println("****************");
					TextView chooseTeam = (TextView) view.findViewById(R.id.chooseTeam);
					teamText.setText(chooseTeam.getText().toString());
					popupWindow.dismiss();
				}
			});  
			//当弹出框隐藏的时候，改变图片方向
			popupWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					addTeamImgaeDownPop.setImageResource(R.drawable.down_popupwindow);
				}
			});
		}
	}
	/*************初始化list集合************/
	public static void initList(){
		
		/***********判断是否连接网络**********************/
		if(!CheckedNetWork.checkedConnection(context)){
			return;
		}
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("userName", curUserName);
		map.put("action", "getHead");
		String resultString = null;
		try {
			resultString = HttpUtil.postRequest(url, map);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if(resultString==null){
			return;
		}
		if (resultString.length()==0) {
			//			android:src="@drawable/touxiang"
			userImage.setImageResource(R.drawable.touxiang);
		}else {
//			System.err.println("??????????????????????????"+resultString);
			fb = FinalBitmap.create(context);
			fb.closeCache();
			fb.display(userImage, resultString);
			
		}
		System.out.println(curUserName);
		AjaxParams params = new AjaxParams();
		params.put("user_name", curUserName);
		params.put("action", "query");
		FinalHttp fh = new FinalHttp();
		fh.post(url, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				super.onFailure(t, strMsg);
				Toast.makeText(context, "加载项目失败", Toast.LENGTH_LONG).show();
			}
			@Override
			public void onSuccess(String t) {
				System.out.println("t = "+t);
				String[] string = new String[]{"project_name","project_outOfDate","project_creator","project_team"};
				try {
					JSONObject object = new JSONObject(t);
					JSONArray array = object.getJSONArray("projectListJson");
					System.out.println("*********"+array.length());
					list.clear();
					for (int j = 0; j < array.length(); j++) {
						JSONObject object3 = array.getJSONObject(j);
						JSONArray array2 = object3.getJSONArray("projectListJson"+j);
						System.out.println("*********"+array2.length());

						Map<String , String> map = new HashMap<String, String>();
						map.put("name", array2.getJSONObject(0).getString(string[0]));
						System.out.println("####"+map.get("name"));
						map.put("out_Time", array2.getJSONObject(1).getString(string[1]));
						System.out.println("####"+map.get("out_Time"));
						map.put("creator", array2.getJSONObject(2).getString(string[2]));
						System.out.println("####"+map.get("creator"));
						map.put("team", array2.getJSONObject(3).getString(string[3]));
						System.out.println("####"+map.get("team"));
						list.add(map);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//刷新数据
				adapter.notifyDataSetChanged();
				super.onSuccess(t);
			}
		});
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
			DialogTool.existDialog(this);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onStart() {
		list.clear();
		initList();
		/*************启动Service接收服务器端发送的消息***********************/
		int temp =sharedPreferences.getInt(curUserName+"PushState", 0);
		if(temp==0){
			Intent serviceIntent = new Intent(this, ReceiveMessageService.class);
			// 启动服务
//			context.startService(serviceIntent);
			startService(serviceIntent);
			Toast.makeText(this, "后台消息推送已启动！", Toast.LENGTH_SHORT).show();
			System.out.println("serviceserviceserviceserviceserviceserviceserviceserviceserviceservice");
		}else {
			Toast.makeText(this, "后台消息推送已关闭！", Toast.LENGTH_SHORT).show();
		}
		super.onStart();
	}
}
